 // 载入数据
 d3.csv('./data/电站地理位置及资金分布.csv').then(data => {
  // 获取容器宽度
  const container = d3.select('.right-container');
  let containerWidth = parseInt(container.style('width'))-10;
  let containerHeight = parseInt(container.style('height'));
  // 初始化 SVG
  const svg = d3.select('#bar-svg')
      .attr('width', containerWidth)
      .attr('height', containerHeight);
  
  const margin = { top: 0, right: 70, bottom: 20, left: 100 };
  let innerWidth = containerWidth - margin.left - margin.right;
  let innerHeight = containerHeight - margin.top - margin.bottom;

  const mainGroup = svg.append('g')
      .attr('transform', `translate(${margin.left}, ${margin.top})`);

  const xValue = d => parseInt(d['电站容量(千瓦)']);
  const yValue = d => d.电站名称;

  const xScale = d3.scaleLinear();
  const yScale = d3.scaleBand();

  // 按 "并网时间" 排序数据
  data.sort((a, b) => new Date(a['并网时间']) - new Date(b['并网时间']));

  // 计算比例尺
  yScale.domain(data.map(yValue)).range([0, innerHeight]).padding(0.1);
  xScale.domain([0, d3.max(data, xValue)]).range([0, innerWidth]);

  // 添加矩形条
  const bars = mainGroup.selectAll('rect')
      .data(data)
      .join('rect')
      .attr('height', yScale.bandwidth())
      .attr('width', 0)  // 初始宽度为 0 以动画展开
      .attr('x', 0)
      .attr('y', d => yScale(yValue(d)))
      .style('fill', '#66b3ff')
      .transition()
      .duration(1000)
      .delay((d, i) => i * 100)
      .attr('width', d => xScale(xValue(d)));  // 过渡到最终宽度

  // 添加坐标轴
  const xAxisGroup = mainGroup.append('g').call(d3.axisBottom(xScale));
  const yAxisGroup = mainGroup.append('g').call(d3.axisLeft(yScale));

  // X 轴位置
  xAxisGroup.attr('transform', `translate(0, ${innerHeight})`);

  // 监听窗口变化，调整 SVG 尺寸
  window.addEventListener('resize', () => {
      containerWidth = parseInt(container.style('width'));
      containerHeight = parseInt(container.style('height'));
      innerWidth = containerWidth - margin.left - margin.right;
      innerHeight = containerHeight - margin.top - margin.bottom;
      svg.attr('width', containerWidth).attr('height', containerHeight);
      xScale.range([0, innerWidth]);
      yScale.range([0, innerHeight]);
      // 更新条形图宽度
      mainGroup.selectAll('rect')
          .attr('width', d => xScale(xValue(d)))
          .attr('y', d => yScale(yValue(d)))
          .attr('height', yScale.bandwidth());

      // 更新 X 轴
      xAxisGroup.attr('transform', `translate(0, ${innerHeight})`)
      .call(d3.axisBottom(xScale));

      yAxisGroup.call(d3.axisLeft(yScale));
  });
});